<?php
/**
 * 功能描述：	权限管理
 * @datetime	2022-08-28
 * @version   	v2.3
 * @author   	ZHL
 * @copyrigh  	2022 ZHL 版权所有
 */

class Admin_PowerServe extends Model {

    /**
     * Notes:获取所有角色-列表
     * User: ZhuHaili
     */
    public function powerRoleList(){
        return $this->conn('mysql')->listData('sysrole', array('status'=>1));
    }

    /**
     * Notes:获取信息
     * User: ZhuHaili
     */
    public function getEssayInfo($mould, $where){
        return $this->conn('mysql')->findData($mould, $where);
    }

    /**
     * Notes:通用分页列表-单表查询
     * User: ZhuHaili
     */
    function getRoleListsPage($mouldCode, $pageNo, $search){
        $orderby = 'a.viewseq desc,a.id asc,a.createdate asc';
        // 查询条件
        $searchInfo = SYS_SESSIONS_GET($mouldCode.'_search_info');
        $whereAdd = $searchInfo ? $searchInfo : array();
        if(!empty($search) && is_array($search)){
            $whereAdd = array();
            foreach($search as $k=>$v){
                if($k == 'search_title' && $v){
                    $whereAdd['locate']['a.title'] = $v;
                }else if($k == 'search_status' && $v){
                    $whereAdd['where']['a.status'] = $v;
                }else if($k == 'search_startdate' && $v){
                    $whereAdd['gts']['a.createdate'] = $v;
                }else if($k == 'search_enddate' && $v){
                    $whereAdd['lts']['a.createdate'] = $v;
                }
            }
            SYS_SESSIONS_SET($mouldCode.'_search_info', $whereAdd);
        }
        $powerM = new Admin_PowerModel();
        // 分页条数
        $limit = 20;
        if(isset($GLOBALS['ADMIN']['sys_pages']) && intval($GLOBALS['ADMIN']['sys_pages'])){
            $limit = intval($GLOBALS['ADMIN']['sys_pages']);
        }
        // 分页计算
        $counts = $powerM->getListsCount($mouldCode, $whereAdd);
        $pageSum = $counts ? ceil($counts/$limit) : 1;    // 总页数
        $pageSum = $pageSum > 1 ? $pageSum : 1;
        $pageNo = $pageNo > $pageSum ? $pageSum : $pageNo; // 最大页数==总页数
        $start = $pageNo * $limit - $limit;
        $pages['counts'] = $counts;
        $pages['pageNo'] = $pageNo;
        $pages['pageSum'] = $pageSum;
        // 获取列表数据
        $list = $powerM->getListsPage($mouldCode, $whereAdd, $start, $limit, $orderby);
        $statusArr = BaseData::$statusArr;
        foreach($list as $k=>$v){
            $list[$k]['statustxt'] = isset($statusArr[$v['status']]) ? $statusArr[$v['status']] : $v['status'];
        }
        $result['list'] = $list;
        $result['pages'] = $pages;
        $result['where'] = $whereAdd;
        return $result;
    }

    /**
     * Notes:权限功能分页列表
     * User: ZhuHaili
     */
    function getFunsListsPage($mouldCode, $pageNo, $search){
        $orderby = 'a.viewseq desc,a.id desc';
        // 查询条件
        $searchInfo = SYS_SESSIONS_GET($mouldCode.'_search_info');
        $whereAdd = $searchInfo ? $searchInfo : array();
        if(!empty($search) && is_array($search)){
            $whereAdd = array();
            foreach($search as $k=>$v){
                if($k == 'search_title' && $v){
                    $whereAdd['locate']['a.title'] = $v;
                }else if($k == 'search_status' && $v){
                    $whereAdd['where']['a.status'] = $v;
                }else if($k == 'search_startdate' && $v){
                    $whereAdd['gts']['a.createdate'] = $v;
                }else if($k == 'search_enddate' && $v){
                    $whereAdd['lts']['a.createdate'] = $v;
                }else if($k == 'search_group' && $v){
                    $whereAdd['where']['a.menu_id'] = $v;
                }

            }
            SYS_SESSIONS_SET($mouldCode.'_search_info', $whereAdd);
        }
        $powerM = new Admin_PowerModel();
        // 分页条数
        $limit = 20;
        if(isset($GLOBALS['ADMIN']['sys_pages']) && intval($GLOBALS['ADMIN']['sys_pages'])){
            $limit = intval($GLOBALS['ADMIN']['sys_pages']);
        }
        // 分页计算
        $counts = $powerM->getListsCount($mouldCode, $whereAdd);
        $pageSum = $counts ? ceil($counts/$limit) : 1;    // 总页数
        $pageSum = $pageSum > 1 ? $pageSum : 1;
        $pageNo = $pageNo > $pageSum ? $pageSum : $pageNo; // 最大页数==总页数
        $start = $pageNo * $limit - $limit;
        $pages['counts'] = $counts;
        $pages['pageNo'] = $pageNo;
        $pages['pageSum'] = $pageSum;
        // 获取列表数据
        $list = $powerM->getFunListsPage($mouldCode, $whereAdd, $start, $limit, $orderby);
        $statusArr = BaseData::$statusArr;
        foreach($list as $k=>$v){
            if(!$v['menuname']){
                $list[$k]['menuname'] = $v['menuname2'] ? $v['menuname2'] : ($v['menu_id'] == 0 ? 'ALL' : $v['menu_id']);
            }
            $list[$k]['statustxt'] = isset($statusArr[$v['status']]) ? $statusArr[$v['status']] : $v['status'];
        }
        $result['list'] = $list;
        $result['pages'] = $pages;
        $result['where'] = $whereAdd;
        return $result;
    }

    /**
     * Notes:列表导出-单表查询
     * User: ZhuHaili
     */
    function getListExecl($mouldCode, $pageNo, $idStr, $search, $thList, $orderby){
        // 查询条件
        $searchInfo = SYS_SESSIONS_GET($mouldCode.'_search_info');
        $whereAdd = $searchInfo ? $searchInfo : array();
        if(!empty($search) && is_array($search)){
            $whereAdd = array();
            foreach($search as $k=>$v){
                if($k == 'search_title' && $v){
                    $whereAdd['locate']['a.title'] = $v;
                }else if($k == 'search_status' && $v){
                    $whereAdd['a.status'] = $v;
                }else if($k == 'search_startdate' && $v){
                    $whereAdd['gts']['a.createdate'] = $v;
                }else if($k == 'search_enddate' && $v){
                    $whereAdd['lts']['a.createdate'] = $v;
                }
            }
            SYS_SESSIONS_SET($mouldCode.'_search_info', $whereAdd);
        }
        if($idStr){
            $whereAdd['in']['a.id'] = $idStr;
        }
        $powerM = new Admin_PowerModel();
        $start = 0;
        $limit = 0;
        if($pageNo){
            // 分页条数
            $limit = 20;
            if(isset($GLOBALS['ADMIN']['sys_pages']) && intval($GLOBALS['ADMIN']['sys_pages'])){
                $limit = intval($GLOBALS['ADMIN']['sys_pages']);
            }
            // 计算分页
            $counts = $powerM->getListsCount($mouldCode, $whereAdd);
            $pageSum = $counts ? ceil($counts/$limit) : 1;    // 总页数
            $pageSum = $pageSum > 1 ? $pageSum : 1;
            $pageNo = $pageNo > $pageSum ? $pageSum : $pageNo; // 最大页数==总页数
            $start = $pageNo * $limit - $limit;
        }
        $thList['createdate'] = '创建时间';
        $trList = $powerM->getListExecl($mouldCode, $whereAdd, $start, $limit, $orderby);
        $statusArr = BaseData::$statusArr;
        foreach($trList as $k=>$v){
            $trList[$k] = $v;
            $trList[$k]['statustxt'] = isset($statusArr[$v['status']]) ? $statusArr[$v['status']] : $v['status'];
        }
        return array('thList'=>$thList,'trList'=>$trList, 'page'=>$pageNo);
    }

    /**
     * Notes:添加内容
     * User: ZhuHaili
     */
    public function addData($mouldCode, $param){
        if(empty($param)){
            return '添加的参数不能为空';
        }
        if(isset($param['subFlag'])){
            unset($param['subFlag']);
        }
        if(isset($param['c'])){
            unset($param['c']);
        }
        if($mouldCode == 'syspower'){
            $param['menu_id'] = isset($param['menu_id']) ? $param['menu_id'] : 0;
        }
        $param['createdate'] = date('Y-m-d H:i:s');
        $result = $this->conn('mysql')->addData($mouldCode, $param);
        return $result ? 'Y' : '添加失败';
    }

    /**
     * Notes:修改内容
     * User: ZhuHaili
     */
    public function updateData($mouldCode, $param){
        if(empty($param)){
            return '修改的参数不能为空';
        }
        if(!isset($param['id'])){
            return '请指定要修改的数据';
        }
        $id = intval($param['id']) ? intval($param['id']) : 0;
        if(!$id){
            return '请指定要修改的数据';
        }
        if(isset($param['subFlag'])){
            unset($param['subFlag']);
        }
        if(isset($param['c'])){
            unset($param['c']);
        }
        $param['menu_id'] = isset($param['menu_id']) ? $param['menu_id'] : 0;
        if(isset($param['menu_name'])){
            if($param['menu_name']){
                $param['menu_id'] = $param['menu_name'];
                $param['types'] = 3;
            }
            unset($param['menu_name']);
        }
        $where['id'] = $id;
        $param['createdate'] = date('Y-m-d H:i:s');
        $result = $this->conn('mysql')->updateData($mouldCode, $param, $where);
        return $result ? 'Y' : '修改失败';
    }

    /**
     * Notes:修改内容
     * User: ZhuHaili
     */
    public function updateRoleData($mouldCode, $param){
        if(empty($param)){
            return '修改的参数不能为空';
        }
        if(!isset($param['id'])){
            return '请指定要修改的数据';
        }
        if(!isset($param['title']) || !$param['title']){
            return '角色名称不能为空';
        }
        $id = intval($param['id']) ? intval($param['id']) : 0;
        if(!$id){
            return '请指定要修改的数据';
        }
        if(isset($param['subFlag'])){
            unset($param['subFlag']);
        }
        $where['id'] = $id;
        $data['title'] = $param['title'];
        $data['status'] = isset($param['status']) ? intval($param['status']) : 1;
        $data['viewseq'] = isset($param['viewseq']) ? intval($param['viewseq']) : 0;
        $result = $this->conn('mysql')->updateData($mouldCode, $data, $where);
        return $result ? 'Y' : '修改失败';
    }

    /**
     * Notes:分配权限
     * User: ZhuHaili
     */
    public function roleGiveRule($param){
        if(empty($param)){
            return '参数不能为空';
        }
        if(!isset($param['id'])){
            return '请指定要修改的数据';
        }
        $id = intval($param['id']) ? intval($param['id']) : 0;
        if(!$id){
            return '请指定要修改的数据';
        }
        if(isset($param['subFlag'])){
            unset($param['subFlag']);
        }
        $where['id'] = $id;
        $data = array();
        $data['menu_ids'] = isset($param['classs']) ? implode(',', $param['classs']) : '';
        $data['classfun'] = isset($param['classfun']) ? implode(',', $param['classfun']) : '';
        $data['essayfun'] = isset($param['essayfun']) ? implode(',', $param['essayfun']) : '';
        $result = $this->conn('mysql')->updateData('sysrole', $data, $where);
        return $result ? 'Y' : '修改失败';
    }

    /**
     * Notes:获取用户权限信息
     * User: ZhuHaili
     */
    public function getUserPowerInfo($userId = ''){
        $userId = $userId ? $userId : getUserId();
        $result = array('menu_ids'=>array(),'classfun'=>array(),'essayfun'=>array());
        if(!$userId){
            return $result;
        }
        // 获取最新的权限角色
        $logSer = new Admin_LoginServe();
        $userInfo = $logSer->getUserInfoNo($userId);
        $powerId = isset($userInfo['power_id']) ? $userInfo['power_id'] : 0;
        if(!$powerId){
            return $result;
        }
        $powerInfo = $this->conn('mysql')->findData('sysrole', array('id'=>$powerId));
        if(empty($powerInfo)){
            return $result;
        }
        $result['menu_ids'] = isset($powerInfo['menu_ids']) ? explode(',', $powerInfo['menu_ids']) : array();
        $result['classfun'] = isset($powerInfo['classfun']) ? explode(',', $powerInfo['classfun']) : array();
        $result['essayfun'] = isset($powerInfo['essayfun']) ? explode(',', $powerInfo['essayfun']) : array();
        return $result;
    }

    /**
     * Notes:判断用户权限
     * User: ZhuHaili
     * Date: 2022/8/31
     */
    public function judgeUserPower($controller, $action, $menuId){
        if(!$controller){
            htmlAlert('异常！无权访问');
        }
        if(!$action){
            htmlAlert('异常！无权访问');
        }
        $classFun = $menuId.'_'.$action;
        $essayFun = $menuId.'_'.$action;
        $classAction = $controller.'_'.$action;
        $whiteFun = $GLOBALS['CONFIG']['white_fun'];

        // 权限白名单
        if(in_array($classAction, $whiteFun)){
            return true;
        }

        // 获得用户角色信息
        $powerInfo = $this->getUserPowerInfo();

        // 判断菜单权限
        $msg = '无权限';
        if(!in_array($menuId, $powerInfo['menu_ids'])){
            if(!in_array($controller, $powerInfo['menu_ids'])){
                $this->errMsg('当前菜单'.$msg);
            }
        }

        // 通用文章时直接判断admin_essay类
        if($controller == 'admin_essay'){
            if(!in_array($essayFun, $powerInfo['essayfun'])){
                $this->errMsg('当前文章管理'.$msg);
            }
        }else{
            // 判断类下的方法权限
            if(!in_array($classFun, $powerInfo['classfun'])){
                if(!in_array($classAction, $powerInfo['classfun'])) {
                    $this->errMsg('当前方法'.$msg);
                }
            }
        }
    }

    /**
     * Notes:错误类型
     * User: ZhuHaili
     */
    private function errMsg($msg){
        $subFlag = Fun::input('subFlag');
        if($subFlag == 'Y'){
            Fun::json($msg, true);
        }else{
            htmlAlert($msg);
        }
    }

}